package com.zzxx.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzxx.entity.*;
import com.zzxx.exceptions.UpdateException;
import com.zzxx.mapper.*;
import com.zzxx.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired(required = false)
    private HttpServletRequest request;
    @Autowired
    private ManagerPowerMapper managerPowerMapper;
    @Autowired
    private ActivityScheduleMapper activityScheduleMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private TicketMapper ticketMapper;
    @Autowired
    private RuleMapper ruleMapper;

    @Autowired
    private ActivityScheduleMapper scheduleMapper;
    @Override
    public List<Activity> queryAll() {
        ActivityExample example = new ActivityExample();
        return activityMapper.selectByExample(example);
    }

    @Override
    public Activity queryById(String id) {
        return activityMapper.selectByPrimaryKey(id);
    }

    @Override
    public void packageUac(UserAndCoupons uac, String aid) {
        String uid = uac.getLoginUser().getId();
        Activity activity = activityMapper.selectByPrimaryKey(aid);
        uac.setActivity(activity);
        UserCouponExample ucExample = new UserCouponExample();
        ucExample.createCriteria().andUseridEqualTo(uid);
        List<UserCoupon> userCoupons = userCouponMapper.selectByExample(ucExample);
        userCoupons.forEach(n->{
            if (n.getStatus()==0){
                Coupon coupon = couponMapper.selectByPrimaryKey(n.getCouponid());
                if (coupon.getTargetid().equals(aid)){
                    int day = computedDay(n.getActivetime(), new Date());
                    int lastDay = coupon.getIndate() - day;
                    //如果lastDay<0代表过期，将它删除
                    if (lastDay<0){
                        userCouponMapper.deleteByPrimaryKey(coupon.getId());
                    }else{
                        //没过期就添加进去
                        uac.getCoupons().add(coupon);
                        uac.getLastDays().add(lastDay);
                        uac.getUcIds().add(n.getId());
                    }
                }
            }
        });
        ActivityScheduleExample example=new ActivityScheduleExample();
        example.createCriteria().andActivityidEqualTo(aid);
        List<ActivitySchedule> list = activityScheduleMapper.selectByExample(example);
        Iterator<ActivitySchedule> iterator = list.iterator();
        while (iterator.hasNext()){
            ActivitySchedule t=iterator.next();
            uac.getActivitySchedules().add(t);
            uac.getAsIds().add(t.getId());
        }
    }
    @Override
    public PageInfo<Activity> findPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        ActivityExample activityExample = new ActivityExample();
        List<Activity> list = activityMapper.selectByExample(activityExample);
        PageInfo<Activity> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void addActivity(MultipartFile uploadPic, Activity activity,Manager manager) throws IOException, UpdateException {
        //保存图片
        String originalFilename = uploadPic.getOriginalFilename();
        //获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //如果后缀时.jpg或者.png才解析，否则返回
        if (!".jpg".equals(suffix)&&!".png".equals(suffix)) throw new UpdateException("noPic");
        //生成保存目录
        String parent = request.getServletContext().getRealPath("work\\activityPic")+"\\"+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String newImageName = UUID.randomUUID().toString().replaceAll("-","")+suffix;
        File gymImageFile = new File(parent, newImageName);
        if (!gymImageFile.getParentFile().exists()) {
            gymImageFile.getParentFile().mkdirs();
        }
        uploadPic.transferTo(gymImageFile);
        //保存src
        String src = "\\"+gymImageFile.getAbsolutePath().substring(gymImageFile.getAbsolutePath().lastIndexOf("work"));
        activity.setSrc(src);

        activity.setId(UUID.randomUUID().toString().replaceAll("-",""));
        //保存场馆
        activityMapper.insert(activity);
        //生成权限信息
        ManagerPower managerPower = new ManagerPower();
        managerPower.setId(UUID.randomUUID().toString().replaceAll("-",""));
        managerPower.setManagerid(manager.getId());
        managerPower.setPowertype(1);
        managerPower.setPowerid(activity.getId());
        managerPower.setPowerlevel(3);
        //保存权限信息
        managerPowerMapper.insert(managerPower);
    }

    @Override
    public void delete(String aid, String mid) throws UpdateException {
        //查看有无权限
        ManagerPowerExample powerExample = new ManagerPowerExample();
        powerExample.createCriteria().andPowertypeEqualTo(1).andPoweridEqualTo(aid).andManageridEqualTo(mid).andPowerlevelGreaterThanOrEqualTo(3);
        List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(powerExample);
        if (managerPowers.size()==0) throw new UpdateException("noPower");
        //删除场馆
        activityMapper.deleteByPrimaryKey(aid);
        //删除票
        TicketExample ticketExample = new TicketExample();
        ticketExample.createCriteria().andTargetidEqualTo(aid);
        ticketMapper.deleteByExample(ticketExample);
        //删除权限信息
        ManagerPowerExample powerExample1 = new ManagerPowerExample();
        powerExample1.createCriteria().andPoweridEqualTo(aid);
        managerPowerMapper.deleteByExample(powerExample1);
    }

    @Override
    public ActivityAndRule findAar(String managerId, String aid) {
        //验证权限
        ManagerPowerExample mexample = new ManagerPowerExample();
//        String aid = activityMapper.selectByPrimaryKey(ticketMapper.selectByPrimaryKey(aid).getTargetid()).getId();
        mexample.createCriteria().andManageridEqualTo(managerId).andPoweridEqualTo(aid).andPowerlevelGreaterThanOrEqualTo(2);
        List<ManagerPower> mp = managerPowerMapper.selectByExample(mexample);
        if (mp.size()!=1) return null;
        //创建Tar
        ActivityAndRule tar = new ActivityAndRule();
        //查找ticket
        Activity activity = activityMapper.selectByPrimaryKey(aid);
        tar.setActivity(activity);
        //查找rule
        RuleExample example = new RuleExample();
        example.createCriteria().andTargetidEqualTo(aid);
        List<Rule> rules = ruleMapper.selectByExample(example);
        if (rules.size()!=1) return null;
        tar.setRule(rules.get(0));
        return tar;
    }

    @Override
    public void updateAar(ActivityAndRule aar) {
        //修改票信息
        Activity activity = aar.getActivity();
        activityMapper.updateByPrimaryKey(activity);
        //修改规则信息
        Rule rule = aar.getRule();
        ruleMapper.updateByPrimaryKey(rule);
    }

    @Override
    public void updateById(MultipartFile uploadPic, Activity activity, Manager loginManager) throws IOException, UpdateException {
        //查看是否有权限更改
        ManagerPowerExample example = new ManagerPowerExample();
        example.createCriteria().andManageridEqualTo(loginManager.getId()).andPoweridEqualTo(activity.getId()).andPowerlevelGreaterThanOrEqualTo(3);
        List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(example);
        if (managerPowers.size()!=1) throw new UpdateException("noPower");
        //有图片更改时保存图片
        if (uploadPic!=null){
            String originalFilename = uploadPic.getOriginalFilename();
            //获取后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //如果后缀时.jpg或者.png才解析，否则返回
            if (!".jpg".equals(suffix)&&!".png".equals(suffix)) throw new UpdateException("noPic");
            //生成保存目录
            String parent = request.getServletContext().getRealPath("work\\activityPic")+"\\"+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String newImageName = UUID.randomUUID().toString().replaceAll("-","")+suffix;
            File activityImageFile = new File(parent, newImageName);
            if (!activityImageFile.getParentFile().exists()) {
                activityImageFile.getParentFile().mkdirs();
            }
            uploadPic.transferTo(activityImageFile);
            //保存src
            String src = "\\"+activityImageFile.getAbsolutePath().substring(activityImageFile.getAbsolutePath().lastIndexOf("work"));
            activity.setSrc(src);
        }
        //保存修改信息
        activityMapper.updateByPrimaryKey(activity);
    }

    @Override
    public List<ActivitySchedule> queryByASid(String id) {
        ActivityScheduleExample activityScheduleExample = new ActivityScheduleExample();
        activityScheduleExample.createCriteria().andActivityidEqualTo(id);
        return scheduleMapper.selectByExample(activityScheduleExample);
    }

    @Override
    public Boolean tui(String id, String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(time);
        ActivityScheduleExample example = new ActivityScheduleExample();
        ActivityScheduleExample.Criteria criteria = example.createCriteria().andActivityidEqualTo(id).andAdateEqualTo(parse);
        List<ActivitySchedule> list = activityScheduleMapper.selectByExample(example);
        ActivitySchedule  activitySchedule=list.get(0);

        Date starttime = activitySchedule.getStarttime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(starttime);
        calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)-16);
        Date time1 = calendar.getTime();
        Date time2 = new Date();
        int i = time2.compareTo(time1);
        if(i==-1){
            return true;
        }else {
            return false;
        }
    }

    //计算d2-d1为多少天
    public int computedDay(Date d1, Date d2){
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        cal1.setTime(d1);
        cal2.setTime(d2);

        //获取日期在一年(月、星期)中的第多少天
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);//第335天
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);//第365天

        //获取当前日期所在的年份
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);

        //如果两个日期的是在同一年，则只需要计算两个日期在一年的天数差；
        //不在同一年，还要加上相差年数对应的天数，闰年有366天

        if(year1 != year2) //不同年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0) //闰年
                {
                    timeDistance += 366;
                }
                else //不是闰年
                {
                    timeDistance += 365;
                }
            }
            System.out.println(timeDistance + (day2-day1));
            return timeDistance + (day2-day1);
        }
        else //同年
        {
            return day2-day1;
        }
    }

    @Override
    public boolean checkPower(String aid, String mid) {
        ManagerPowerExample example = new ManagerPowerExample();
        example.createCriteria().andManageridEqualTo(mid).andPoweridEqualTo(aid).andPowerlevelGreaterThanOrEqualTo(3);
        List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(example);
        return managerPowers.size()==1;
    }

    @Override
    public List<ManagerPower> findPower(String aid, String id) {
        ManagerPowerExample example = new ManagerPowerExample();
        example.createCriteria().andPoweridEqualTo(aid).andManageridNotEqualTo(id);
        List<ManagerPower> list = managerPowerMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<ManagerAndPower> packageMap(List<ManagerPower> list) {
        List<ManagerAndPower> mapList = new ArrayList<>();
        list.forEach(n->{
            ManagerAndPower managerAndPower = new ManagerAndPower();
            managerAndPower.setManagerPower(n);
            String managerid = n.getManagerid();
            Manager manager = managerMapper.selectByPrimaryKey(managerid);
            managerAndPower.setManager(manager);
            mapList.add(managerAndPower);
        });
        return mapList;
    }

    @Override
    public void deleteNum(String id, String num) {
        int n = Integer.parseInt(num);
        ActivitySchedule activitySchedule = activityScheduleMapper.selectByPrimaryKey(id);
        activitySchedule.setFreenum(activitySchedule.getFreenum()-n);
        activityScheduleMapper.updateByPrimaryKey(activitySchedule);
    }
}
